<template>
	<view class="container">
		<up-sticky>
			<up-row customStyle="padding:10px 10px;background:#ffffff;">
				<!-- <up-col span="1">
					<up-icon name="list" size="24" @click="openPicker"></up-icon>
				</up-col> -->
				<up-col span="4" customStyle="font-size:16px;color:#0000ff;">
					<up-loading-icon :show="!caLoaded"></up-loading-icon>
					<view v-show="caLoaded" @click="openPicker">
						<up-text prefixIcon="list-dot" :lines="1" color="blue" iconStyle="font-size:26px;color:blue"
							:text="categoryText" size="18"></up-text>
					</view>
				</up-col>
				<up-col span="1">
					<up-icon name="arrow-right-double" size="16"></up-icon>
				</up-col>
				<up-col span="7">
					<up-search placeholder="搜索关键词" :disabled="true" @click="toSearch"></up-search>
				</up-col>
			</up-row>
		</up-sticky>

		<unicloud-db ref="udb" :collection="collection" getcount
			v-slot:default="{data, pagination, loading, hasMore, error}"
			 :page-size="pageSize" loadtime="onready"
			@load="onListLoad">
			<view v-if="error">{{error.message}}</view>
			<view v-else>
				<uni-list>
					<!--卡片：标题+大图+摘要-->
					<template v-for="(item, index) in articleList" :key="item._id">
						<uni-list-item v-if="(item.viewmode==1)" direction="column" :to="'./detail?id='+item._id">
							<template v-slot:body>
								<uni-card spacing="0" :is-full="true">
									<template v-slot:title>
										<view class="cart_title">
											<text>
												<!-- <text class="pfix" v-if="item.category_id[0].shortname">
													【{{item.category_id[0].shortname}}】
												</text> -->
												{{item.title}}
											</text>
										</view>
									</template>
									<view v-if="item.thumbnail && item.thumbnail.length">
										<image class="thumb_fill" :src="item.thumbnail[0]" mode="aspectFill"></image>
									</view>
									<view class="p_text u-line-5">
										<text>{{item.excerpt}}</text>
									</view>
									<view class="card-actions u-flex-between u-m-t-10" @tap.stop>
										<view class="uni-footer-text">
											{{(item.category_id&&item.category_id.length?
											'【'+item.category_id[0].name+'】':'')}}
											{{timeFrom(item.last_modify_date,'yyyy/mm/dd') + '发布'}}

										</view>
										<view class="uni-footer-text">
											<button class="u-reset-button" style="display:flex;" open-type="share">
												<uni-icons type="pyq" size="18" color="#999"
													style="margin-right: 3px;"></uni-icons>
												<text>分享</text>
											</button>
										</view>
									</view>
									<!-- <view class="card-actions uni-note">
										<view class="card-actions-item" @tap.stop="actionsClick('点赞')">
											{{(item.category_id&&item.category_id.length?'【'+item.category_id[0].name+'】':'')}}
											{{timeFrom(item.last_modify_date,'yyyy/mm/dd') + '发布'}}
										</view>
										<view class="card-actions-item" @tap.stop>
											<button class="u-reset-button" style="display:flex;" open-type="share">
												<uni-icons type="pyq" size="18" color="#999"
													style="margin-right: 3px;"></uni-icons>
												<text>分享</text>
											</button>
										</view>
									</view> -->
									<!-- <template v-slot:actions>
										<view class="card-actions">
											<view class="card-actions-item" @tap.stop>
												
											</view>
											<view class="card-actions-item" @tap.stop="actionsClick('点赞')">
												<uni-icons type="heart" size="18" color="#999"></uni-icons>												
												<text class="card-actions-item-text">点赞</text>
											</view>
											<view class="card-actions-item" @tap.stop="actionsClick('评论')">
												<uni-icons type="chatbubble" size="18" color="#999"></uni-icons>
												<text class="card-actions-item-text">评论</text>
											</view>
										</view>
									</template> -->
								</uni-card>
							</template>
						</uni-list-item>

						<!--viewmode==0-->
						<!--列表：标题-->
						<uni-list-item v-if="!item.viewmode||item.viewmode==0" :to="'./detail?id='+item._id" showArrow>
							<template v-slot:body>
								<text class="u-line-2">
									<text class="pfix" v-if="item.category_id[0].shortname">
										【{{item.category_id[0].shortname}}】
									</text>
									{{item.title}}
								</text>
							</template>
						</uni-list-item>

						<!--viewmode==2-->
						<!--纵排：标题+多图+摘要-->
						<uni-list-item v-if="item.viewmode==2" direction="column" :to="'./detail?id='+item._id">
							<template v-slot:header>
								<view class="cart_title">
									<text>
										<!-- <text class="pfix" v-if="item.category_id[0].shortname">
											【{{item.category_id[0].shortname}}】
										</text> -->
										{{item.title}}
									</text>
								</view>
							</template>
							<!-- 通过body插槽定义列表内容，当前布局会显示多张图片，如果图片为一张，则显示为大图 -->
							<template v-slot:body>
								<view v-if="item.thumbnail&&item.thumbnail.length >= 3" class="content uni-media-box">
									<image v-for="(v,x) in 3" :key="'example_viewmode_2_'+x" class="uni-thumb"
										:src="item.thumbnail[x]" mode="aspectFill"></image>			
								</view>
								<view v-else-if="item.thumbnail&&item.thumbnail.length==1"
									class="content">
									<image class="thumb_fill" :src="item.thumbnail[0]" mode="aspectFill"></image>
								</view>
								<view class="u-m-t-20 p_text p_font u-line-5">
									<text>{{item.excerpt}}</text>
								</view>
							</template>
							<!-- 通过footer插槽定义列表底部内容 -->
							<template v-slot:footer>
								<view class="uni-footer" @tap.stop>
									<view class="uni-footer-text">
										{{(item.category_id&&item.category_id.length?
										'【'+item.category_id[0].name+'】':'')}}
										{{timeFrom(item.last_modify_date,'yyyy/mm/dd') + '发布'}}

									</view>
									<view class="uni-footer-text">
										<button class="u-reset-button" style="display:flex;" open-type="share">
											<uni-icons type="pyq" size="18" color="#999"
												style="margin-right: 3px;"></uni-icons>
											<text>分享</text>
										</button>
									</view>
								</view>
							</template>
						</uni-list-item>
						<!--viewmode==2-->

						<!--viewmode==3-->
						<!--横排：左缩略图+右标题-->
						<uni-list-item v-if="item.viewmode==3" direction="row" :title="item.title"
							:note="(item.category_id&&item.category_id.length?'【'+item.category_id[0].name+'】':'') + timeFrom(item.last_modify_date,false) + '发布'"
							:to="'./detail?id='+item._id">
							<!-- 通过header插槽定义列表左侧的图片显示，其他内容通过List组件内置属性实现-->
							<template v-slot:header>
								<view class="uni-thumb">
									<image :src="item.thumbnail&&item.thumbnail.length?item.thumbnail[0]:''"
										mode="aspectFill"></image>
								</view>
							</template>
						</uni-list-item>
						<!--viewmode==3-->

						<!--viewmode==4-->
						<!--横排：左标题+右缩略图-->
						<uni-list-item v-if="item.viewmode==4" direction="row" :to="'./detail?id='+item._id">
							<!-- 通过body插槽定义列表内容显示 -->
							<template v-slot:body>
								<view class="uni-list-box uni-content">
									<view class="uni-title uni-ellipsis-2">
										{{item.title}}
									</view>
									<view class="uni-note">
										<text>{{(item.category_id&&item.category_id.length?'【'+item.category_id[0].name+'】':'')}}</text>
										<text>{{timeFrom(item.last_modify_date,false) + '发布'}}</text>
									</view>
								</view>
							</template>
							<!-- 通过footer插槽自定义图片右侧显示 -->
							<template v-slot:footer>
								<view class="uni-thumb" style="margin: 0;">
									<image :src="item.thumbnail&&item.thumbnail.length?item.thumbnail[0]:''"
										mode="aspectFill"></image>
								</view>
							</template>
						</uni-list-item>
						<!--viewmode==4-->
						<!--viewmode==5 viewmode==6-->
						<!--5混排有图：上标题+左图摘要-->
						<!--6混排无图：上标题+摘要-->
						<uni-list-item v-if="item.viewmode==5 || item.viewmode==6" direction="column"
							:to="'./detail?id='+item._id">
							<!-- 通过header插槽定义列表的标题 -->
							<template v-slot:header>
								<view class="uni-title">{{item.title}}</view>
							</template>
							<!-- 通过body插槽定义列表内容显示 -->
							<template v-slot:body>
								<view class="uni-list-box">
									<view v-if="item.viewmode==5&&item.thumbnail&&item.thumbnail.length"
										class="uni-thumb">
										<image :src="item.thumbnail[0]" mode="aspectFill"></image>
									</view>
									<view class="uni-content">
										<view class="uni-title-sub u-line-4">{{item.excerpt}}</view>
									</view>
								</view>
							</template>
							<!-- 同步footer插槽定义列表底部的显示效果 -->
							<template v-slot:footer>
								<view class="uni-footer" @tap.stop>
									<view class="uni-footer-text">
										{{(item.category_id&&item.category_id.length?
										'【'+item.category_id[0].name+'】':'')}}
										{{timeFrom(item.last_modify_date,'yyyy/mm/dd') + '发布'}}

									</view>
									<view class="uni-footer-text">
										<button class="u-reset-button" style="display:flex;" open-type="share">
											<uni-icons type="pyq" size="18" color="#999"
												style="margin-right: 3px;"></uni-icons>
											<text>分享</text>
										</button>
									</view>
								</view>
							</template>
						</uni-list-item>
						<!--viewmode==5 6-->

					</template>
				</uni-list>
			</view>
			<uni-load-more :contentText="loadMore"
				:status="loading?'loading':(hasMore ? 'more' : 'noMore')"></uni-load-more>
		</unicloud-db>
		<up-picker :show="showCO" :columns="categoryList" title="只显示选定类别内容" visibleItemCount="12" keyName="text"
			@cancel="showCO=false" @confirm="pickerHandle" @close="showCO=false" ref="picker"></up-picker>
	</view>
</template>

<script setup>
	//import { xasaStore } from '@/stores'
	import {
		parseImageUrl
	} from '@/common/cloud/parse-image-url.js';
	import {
		ref,
		computed,
		getCurrentInstance
	} from 'vue';
	import {
		/* onLoad, */
		onReady,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app';

	import {
		timeFrom
	} from '@/uni_modules/uview-plus';

	// 页面可以通过定义 props 来直接接收 url 传入的参数
	// 如：uni.navigateTo({ url: '/pages/index/index?menu_id=xasa-articles&t=典型案例' })
	const props = defineProps({
		menu_id: String,
		t: String // 用于区分不同页面的标题，例如：'典型案例'、'新闻动态'、'通知公告'等。
	});
	
	const instance = getCurrentInstance().proxy;
	const eventChannel = instance.getOpenerEventChannel();
	/* eventChannel.on('E_HandleMenu', function(data) {
	    console.log("data.name",data.name)
	}) */

	// 页面可以通过 defineExpose 方法来暴露需要传递给页面的数据。
	
	const db = uniCloud.databaseForJQL();
	const T1 = 'xasa-example';
	const T2 = 'xasa-categories';
	const T3 = 'xasa-index-menus';
	const T4 = 'uni-id-users';
	const OrderBy = 'last_modify_date desc';
	const pageSize = 20;

	let udb = ref(null);

	let articleList = ref([]);
	let loading = ref(false);
	let hasMore = ref(true);
	let networkType = ref("");
	let mtitle = props.t;
	let caLoaded = ref(false);
	let showCO = ref(false);
	let picker = ref(null);
	let curCategory_id = ref('');
	let categoryText = ref('全部类别');

	const loadMore = {
		contentdown: "",
		contentrefresh: "正在加载...",
		contentnomore: '该类目下无更多数据了'
	};
	let categoryList = [
		[{
			"_id": "",
			"sort": 0,
			"text": "全部类别"
		}, ]
	];

	const collection = computed(() => {
		const mid = props.menu_id;
		const id = curCategory_id.value;
		let w = {
			article_status: 1
		}
		if (mid) Object.assign(w, {
			menu_id: mid
		});
		if (id) Object.assign(w, {
			category_id: id
		});

		return [
			db.collection(T1).where(w).field(
				'thumbnail,menu_id,category_id,title,viewmode,excerpt,comment_status,last_modify_date')
			.orderBy(OrderBy).getTemp(),
			db.collection(T2).field('_id,name,shortname,icon').getTemp(),
			db.collection(T3).field('name,menu_id').getTemp()
		]
	});

	const store = getCurrentInstance().appContext.config.globalProperties.$xasaStore;
	store.getCats().then((res) => {
		categoryList = [
			[{
				"_id": "",
				"text": "全部类别",
				"sort": 0
			}, ...res.data]
		];
		caLoaded.value = true
	});
	store.getMenus().then((res) => {
		const m = res.data.find(x => x.menu_id == props.menu_id) || {};
		mtitle = m.name || mtitle;
		uni.setNavigationBarTitle({
			title: mtitle
		})
	});

	async function onListLoad(data, ended, pagination) {
		const listData = data;
		// 处理cloud://文件链接
		for (let item of listData) {
			const imgs = await parseImageUrl(item.thumbnail)
			if (imgs != null) {
				item.thumbnail = imgs.map(x => x.src)
			}
			item.viewmode = item.viewmode || 0;
		}

		if (pagination.current == 1) {
			articleList.value = data;
		} else {
			articleList.value.concat(data);
		}
	}

	function checkNetwork() {
		uni.getNetworkType({
			success: (res) => {
				networkType = res.networkType;
			}
		})
	}
	function previewCover(imageList,cur=0) {
		uni.previewImage({
			current: imageList[cur],
			urls: imageList
		})
	}
	function toSearch(e) {
		uni.navigateTo({
			url: '/pages/search/search?menu_id=' + props.menu_id + '&cid=' + curCategory_id.value
		})
	}

	function toDetail(id) {
		uni.navigateTo({
			url: './detail?id=' + id
		})
	}

	function openPicker(e) {
		showCO.value = true
	}
	const pickerHandle = (e) => {
		//const {indexs,value,values}=e;
		const {
			value
		} = e; // 获取选择的分类ID，并更新查询条件。

		const id = value[0]._id,
			t = value[0].text; // 更新查询条件，并重新加载数据。
		if (curCategory_id.value !== id) {
			curCategory_id.value = id; // 更新查询条件，并重新加载数据。
			categoryText.value = t; // 更新查询条件，并重新加载数据。
			uni.setNavigationBarTitle({
				title: `${mtitle}(${t})`
			})
		}
		showCO.value = false; // 关闭分类选择器。
	};
	const actionsClick = (text) => {
		uni.showToast({
			title: text,
			icon: 'none'
		})
	};

	/* 	const loadCategories = () => {
			db.collection(T2).field('name as text,sort').orderBy('sort').get().then(
				res => {
					categoryList = [
						[{
							"_id": "",
							"text": "全部类别",
							"sort": 0
						}, ...res.data]
					]
				}).catch(err => {
				console.error(err);
			})
	}; */

	/*onLoad(() => {
			//loadCategories()
	});*/
	onReady(() => {

		udb.value.loadData({
			clear: true
		})
	});
	onReachBottom(() => {
		console.log('onReachBottom')
		udb.value.loadMore()
	});
	onPullDownRefresh(() => {
		udb.value.loadData({
			clear: true
		}, () => {
			uni.stopPullDownRefresh()
		})
	});
</script>
<style lang="scss">
	@import '@/common/css/uni-ui.scss';

	image {
		will-change: transform;
	}

	.thumb_fill {
		height: 180px;
		width: 100%;
	}

	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #efeff4;
		min-height: 100%;
		height: auto;
	}

	.pfix {
		color: #aaa;
	}

	.m_tb_10 {
		margin: 10px 0;
	}

	.p_text {
		text-align: justify;
		text-align-last: left;
		text-indent: 2em;
	}

	.p_font {
		font-size: 90%;
		color: #666;
		line-height: 150%;
	}


	.cart_title {
		font-size: 16px;
		font-weight: bold;
		padding: 10px;
	}

	.custom-cover {
		flex: 1;
		flex-direction: row;
		position: relative;
	}

	.cover-content {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 40px;
		background-color: rgba($color: #000000, $alpha: 0.4);
		display: flex;
		flex-direction: row;
		align-items: center;
		padding-left: 15px;
		font-size: 14px;
		color: #fff;
	}

	.cover-image {
		flex: 1;
		height: 150px;
	}

	.card-actions-item {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.card-actions-item-text {
		font-size: 12px;
		color: #666;
		margin-left: 5px;
	}

	.card-actions {
		display: flex;
		flex-direction: row;
		/* justify-content: space-around; */
		align-items: center;
		height: 45px;
		border-top: 1px #eee solid;
	}

	.tips {
		color: #67c23a;
		font-size: 14px;
		line-height: 40px;
		text-align: center;
		background-color: #f0f9eb;
		height: 0;
		opacity: 0;
		transform: translateY(-100%);
		transition: all 0.3s;
	}

	.tips-ani {
		transform: translateY(0);
		height: 40px;
		opacity: 1;
	}

	.content {
		width: 100%;
		display: flex;
	}

	.list-picture {
		width: 100%;
		height: 145px;
	}

	.thumb-image {
		width: 100%;
		height: 100%;
	}

	.ellipsis {
		display: flex;
		overflow: hidden;
	}

	.uni-ellipsis-1 {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.uni-ellipsis-2 {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}
</style>